package org.richin.servlet.Filter.util;

import java.io.CharArrayWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class FileCaptureFilter implements Filter {
	private String filePath;

	public void init(FilterConfig filterConfig) throws ServletException {
		filePath = filterConfig.getServletContext().getRealPath("/") + "/WEB-INF";
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		String fileName = filePath + ((HttpServletRequest) request).getServletPath() + ".html";
		System.out.println(fileName);
		PrintWriter out = response.getWriter();
		FileCaptureResponseWrapper responseWrapper = new FileCaptureResponseWrapper((HttpServletResponse) response);
		chain.doFilter(request, responseWrapper);
		responseWrapper.writeFile(fileName);// 输出到文件
		responseWrapper.writeResponse(out); // 显示到浏览器
	}

	public void destroy() {
	}

	class FileCaptureResponseWrapper extends HttpServletResponseWrapper {
		private CharArrayWriter output;

		public String toString() {
			return output.toString();
		}

		public FileCaptureResponseWrapper(HttpServletResponse response) {
			super(response);
			output = new CharArrayWriter();
		}

		public PrintWriter getWriter() {
			return new PrintWriter(output);
		}

		public void writeFile(String fileName) throws IOException {
			FileWriter fw = new FileWriter(fileName);
			fw.write(output.toCharArray());
			fw.close();
		}

		public void writeResponse(PrintWriter out) {
			out.print(output.toCharArray());
		}
	}
}
